//
//  HomeViewController.m
//  YunGou
//
//  Created by macbook on 16/5/16.
//  Copyright © 2016年 macbook. All rights reserved.
//

#import "HomeViewController.h"
#import "HomeProductCell.h"
#import "ProductViewController.h"
#import "ShowOrderViewController.h"
#import "BuyRecordViewController.h"
#import "RechargeViewController.h"
#import "GoodsDetailViewController.h"
#import "HomeAnnounceCell.h"
#import "HomeSectionHeader.h"
#import "SDCycleScrollView.h"
#import "NSObject+Tools.h"
#import "ProductModel.h"
#import "NetWorkTool.h"
#import "TopScrollViewModel.h"
#import <UIImageView+WebCache.h>
#import "MZTimerLabel.h"
#import <MJRefresh.h>

#define RecommendCell @"ReuseIdentifier"

@interface HomeViewController ()<UITableViewDelegate,UITableViewDataSource,MZTimerLabelDelegate>
@property (weak, nonatomic) IBOutlet UIView *chooseItemView;
@property (weak, nonatomic) IBOutlet SDCycleScrollView *topScrollView;
@property (nonatomic,strong) NSMutableArray *NewProductArray;
//最新揭晓
@property (nonatomic,strong) NSMutableArray *latestAnnounceArray;
//头部滚动视图
@property (nonatomic,strong) NSMutableArray *topScArray;

@property (nonatomic,assign) NSInteger currentCount;
@end

@implementation HomeViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self createUI];
    
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        [self loadHot];
        [self loadLatestAnnounce];
    }];
    
    _topScArray = [NSMutableArray array];
    NSMutableArray *imagePathArray = [NSMutableArray array];
    [NetWorkTool topScrollViewWithSuccess:^(id object) {
        if ([object[@"code"] integerValue] == 1) {
            for (NSDictionary *dict in object[@"data"][@"first_banner_data"]) {
                TopScrollViewModel *model = [TopScrollViewModel modelWithDict:dict];
                [_topScArray addObject:model];
                [imagePathArray addObject:[ImageUrl stringByAppendingString:model.img]];
            }
            _topScrollView.imageURLStringsGroup = imagePathArray;
        }
    } failure:^(NSError *error) {
        
    }];
    _topScrollView.currentPageDotColor = ThemeColor;
    
    [self loadHot];
}

- (void)loadHot{
    [MBProgressHUD showMessage:@"正在加载" toView:self.tabBarController.view];
    [NetWorkTool hotRecommendWithStart:0 success:^(id object) {
        if ([object[@"code"] integerValue] == 1) {
            [MBProgressHUD hideHUDForView:self.tabBarController.view];
            [self.tableView.mj_header endRefreshing];
            NSArray *dataArray = object[@"data"];
            _NewProductArray = [NSMutableArray array];
            for (NSDictionary *dataDict in dataArray) {
                ProductModel *productModel = [ProductModel modelWithDict:dataDict];
                [_NewProductArray addObject:productModel];
            }
        }
        [self loadLatestAnnounce];
    } failure:^(NSError *error) {
        [MBProgressHUD hideHUDForView:self.tabBarController.view];
    }];
}

//加载最新揭晓
- (void)loadLatestAnnounce{
    _latestAnnounceArray = [NSMutableArray array];
    _currentCount = 0;
    [NetWorkTool mainLatestAnnounceWithSuccess:^(id object) {
        if ([object[@"code"] integerValue] == 1) {
            for (NSDictionary *dict in object[@"data"]) {
                ProductModel *model = [ProductModel modelWithDict:dict];
                
                ////just test
//                NSDate *nowDate = [NSDate date];
//                NSTimeInterval nowTime = [nowDate timeIntervalSince1970];
//                model.q_end_time = nowTime + 5;
                ///
                [_latestAnnounceArray addObject:model];
            }
        }
        [self.tableView reloadData];
    } failure:^(NSError *error) {
        
    }];
}

- (void)createUI{
    //为每个view添加手势
    for (UIView *itemView in _chooseItemView.subviews) {
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleTap:)];
        [itemView addGestureRecognizer:tap];
    }
    
    [self.tableView registerNib:[UINib nibWithNibName:@"HomeProductCell" bundle:nil] forCellReuseIdentifier:RecommendCell];
}

//选项卡的点击事件
- (void)handleTap:(UIGestureRecognizer *)tap{
    NSInteger tag = tap.view.tag;
    switch (tag) {
        case 1:{
            //新品
            ProductViewController *productVC = SB(@"Home", @"ProductVC");
            productVC.title = @"新品";
            productVC.type = NewProduct;
            [self.navigationController pushViewController:productVC animated:YES];
        }break;
        case 2:{
            //晒单
            ShowOrderViewController *showOrderVC = SB(@"Common", @"ShowOrderVC");
            showOrderVC.title = @"晒单分享";
            showOrderVC.isShare = NO;
            showOrderVC.isMine = NO;
            [self.navigationController pushViewController:showOrderVC animated:YES];
        }break;
        case 3:{
            //云购记录
            BuyRecordViewController *recordVC = SB(@"Mine",@"RecordVC");
            [self.navigationController pushViewController:recordVC animated:YES];
        }break;
        default:{
            RechargeViewController *rechargeVC = SB(@"Mine", @"RechargeVC");
            [self.navigationController pushViewController:rechargeVC animated:YES];
        }
            break;
    }
}

-(void)timerLabel:(MZTimerLabel*)timerLabel finshedCountDownTimerWithTime:(NSTimeInterval)countTime{
    
    UIView *view = [timerLabel getAccessoryObject];
    MZTimerLabel *timeLabel = [view viewWithTag:6];
    timeLabel.hidden = YES;
    UILabel *label = [view viewWithTag:8];
    label.hidden = NO;
}

#pragma -mark tablViewDelegate and DataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 3;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (section == 2) {
        return _NewProductArray.count%2 == 0?_NewProductArray.count/2:_NewProductArray.count/2+1;
    }return 1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    UITableViewCell *baseCell = nil;
    if (indexPath.section == 0) {
        baseCell = [tableView dequeueReusableCellWithIdentifier:@"grabCell"];
        //闪夺按钮
        UIButton *quickGrabBtn = [baseCell.contentView viewWithTag:1];
        [quickGrabBtn addTarget:self action:@selector(grabClicked:) forControlEvents:UIControlEventTouchUpInside];
        //巧夺按钮
        UIButton *cleverGrabBtn = [baseCell.contentView viewWithTag:2];
        [cleverGrabBtn addTarget:self action:@selector(grabClicked:) forControlEvents:UIControlEventTouchUpInside];
        
    }else if (indexPath.section == 1){
        HomeAnnounceCell *cell = [tableView dequeueReusableCellWithIdentifier:@"latestCell"];
        if (_latestAnnounceArray.count != 0) {
            
            ProductModel *firstModel = _latestAnnounceArray[0];
            [cell.firstImage sd_setImageWithURL:[NSURL URLWithString:[ImageUrl stringByAppendingString:firstModel.thumb]]];
            cell.firstTitle.text = firstModel.title;
            

            cell.firstTime.hidden = NO;
            cell.firstShow.hidden = YES;
            [cell.firstTime setAccessoryObject:cell.firstView];
            if (!cell.firstTime.counting) {
                [cell.firstTime start];
            }
            cell.firstTime.delegate = self;
            [cell.firstTime setCountDownTime:firstModel.q_end_time - NowTime];
            cell.firstTime.resetTimerAfterFinish = YES;
            cell.firstTime.timeFormat = @"mm:ss SS";
            [cell.firstTime start];
            
            ProductModel *secondModel = _latestAnnounceArray[1];
            [cell.secondImage sd_setImageWithURL:[NSURL URLWithString:[ImageUrl stringByAppendingString:secondModel.thumb]]];
            cell.secondShow.hidden = YES;
            cell.secondTime.hidden = NO;
            if (!cell.secondTime.counting) {
                [cell.secondTime start];
            }
            cell.secondTitle.text = secondModel.title;
            [cell.secondTime setAccessoryObject:cell.secondView];
            cell.secondTime.delegate = self;
            [cell.secondTime setCountDownTime:secondModel.q_end_time - NowTime];
            cell.secondTime.timeFormat = @"mm:ss SS";
            [cell.secondTime start];
            
            ProductModel *thirdModel = _latestAnnounceArray[2];
            [cell.thirdImage sd_setImageWithURL:[NSURL URLWithString:[ImageUrl stringByAppendingString:thirdModel.thumb]]];
            cell.thirdTime.hidden = NO;
            cell.thirdShow.hidden = YES;
            if (!cell.thirdTime.counting) {
                [cell.thirdTime start];
            }
            cell.thirdTitle.text = thirdModel.title;
            [cell.thirdTime setAccessoryObject:cell.thirdView];
            cell.thirdTime.delegate = self;
            [cell.thirdTime setCountDownTime:thirdModel.q_end_time - NowTime];
            cell.thirdTime.timeFormat = @"mm:ss SS";
            [cell.thirdTime start];
            
            cell.announceBlock = ^(NSInteger tag){
                GoodsDetailViewController *goodsDetailVC = SB(@"Common", @"GoodsDetailVC");
                ProductModel *clickModel = _latestAnnounceArray[tag - 1];
                goodsDetailVC.productModel = clickModel;
                
                if (clickModel.q_end_time > NowTime) {
                    goodsDetailVC.detailType = NowAnnounce;
                }else{
                    goodsDetailVC.detailType = HasAnnounce;
                }
                [self.navigationController pushViewController:goodsDetailVC animated:YES];
            };
        }
        baseCell = cell;
    }else{
        HomeProductCell *cell = [tableView dequeueReusableCellWithIdentifier:RecommendCell];
        ProductModel *rightModel = nil;
        if (_NewProductArray.count % 2 == 0) {
            cell.rightView.hidden = NO;
            rightModel = _NewProductArray[indexPath.row * 2 + 1];
            [cell.rightView setAccessoryObject:rightModel];
            [cell.rightImageView sd_setImageWithURL:[NSURL URLWithString:[ImageUrl stringByAppendingString:rightModel.thumb]]];
            cell.rightTitleLabel.text = rightModel.title;
            cell.rightProgressView.progress = rightModel.canyurenshu/rightModel.zongrenshu;
            cell.rightTotalNeedLabel.text = [NSString stringWithFormat:@"总需 %ld",rightModel.zongrenshu];
            cell.rightSurplusLabel.text = [NSString stringWithFormat:@"%ld",rightModel.zongrenshu - rightModel.canyurenshu];
        }else{
            cell.rightView.hidden = YES;
        }
        
        ProductModel *leftModel = _NewProductArray[indexPath.row * 2];
        [cell.leftView setAccessoryObject:leftModel];
        [cell.leftImageView sd_setImageWithURL:[NSURL URLWithString:[ImageUrl stringByAppendingString:leftModel.thumb]]];
        cell.leftTitleLabel.text = leftModel.title;
        cell.leftProgressView.progress = leftModel.canyurenshu/leftModel.zongrenshu;
        cell.leftTotalNeedLabel.text = [NSString stringWithFormat:@"总需 %ld",leftModel.zongrenshu];
        cell.leftSurplusLabel.text = [NSString stringWithFormat:@"%ld",leftModel.zongrenshu - leftModel.canyurenshu];
        
        cell.homeProductCellBlock = ^(UIView *tapView){
            GoodsDetailViewController *goodsDetailVC = SB(@"Common", @"GoodsDetailVC");
            ProductModel *model = [tapView getAccessoryObject];
            goodsDetailVC.productModel = model;
            goodsDetailVC.detailType = DonotAnnounce;
            [self.navigationController pushViewController:goodsDetailVC animated:YES];
        };
        
        cell.addShopCartBlock = ^(NSInteger tag){
            ProductModel *model = nil;
            if (tag == 1) {
                model = leftModel;
            }else{
                model = rightModel;
            }
            [NetWorkTool addShopCartWithGoodsId:model.Id success:^(id object) {
                if ([object[@"code"] integerValue] == 1) {
                    [MBProgressHUD showSuccess:@"添加成功"];
                }
            } failure:^(NSError *error) {
            }];
        };
        baseCell = cell;
    }
    return baseCell;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    if (section == 0) {
        UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, 10)];
        view.backgroundColor = [UIColor whiteColor];
        return view;
    }else if (section == 1 || section == 2) {
        HomeSectionHeader *headerView = [HomeSectionHeader nibInitializtion];
        if (section == 1) {
            headerView.titLabel.text = @"最新揭晓";
            headerView.homeHeaderBlock = ^{
                self.tabBarController.selectedIndex = 2;
            };
        }else{
            headerView.titLabel.text = @"热门推荐";
            headerView.homeHeaderBlock = ^{
                ProductViewController *productVC = SB(@"Home", @"ProductVC");
                productVC.title = @"热门推荐";
                productVC.type = HotRecommend;
                [self.navigationController pushViewController:productVC animated:YES];
            };
        }
        
        return headerView;
    }
    return nil;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 0) {
        return 58;
    }else if (indexPath.section == 1){
        return 135;
    }return 208;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    if (section == 0) {
        return 0.01f;
    }return 30.0f;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    if (section == 2) {
        return 0.01f;
    }
    return 15.0f;
}

//巧夺 闪夺点击
- (void)grabClicked:(UIButton *)btn{
    ProductViewController *productVC = SB(@"Home", @"ProductVC");
    if (btn.tag == 1) {
        productVC.title = @"闪夺";
        productVC.type = ShanDuo;
    }else{
        productVC.title = @"巧夺";
        productVC.type = QiaoDuo;
    }
    [self.navigationController pushViewController:productVC animated:YES];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
